<!-- 推广员列表 -->
<template>
  <div class="promoter sys-content">
    <page-mod>
      <el-card>
        <div class="query-box">
          <el-form :model="query" inline>
            <el-form-item label="手机号:">
              <el-input v-model="query.phone" placeholder="请输入手机号" clearable/>
            </el-form-item>
            <el-form-item label="推广员编号:">
              <el-input v-model="query.dealerCode" placeholder="请输入推广员编号" clearable/>
            </el-form-item>
            <el-form-item label="启用状态:">
              <el-select v-model="query.enableStatus" placeholder="请选择" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
          </el-form>
          <div class="btns">
            <el-button icon="Search" color="#16b777" @click="load(1)">查询</el-button>
            <el-button icon="Plus" color="#FFB800" @click="show = true">新增</el-button>
            <el-button icon="Refresh" color="#FF5722" @click="resetSearch">重置</el-button>
          </div>
        </div>
      </el-card>
    </page-mod>
    <page-mod title="推广员数据" icon="Histogram" :showBtn="false" :padBottom="false">
      <el-card v-loading="loading" element-loading-text="拼命加载中">
        <el-table ref="tableRef" :data="dataList" max-height="493" border>
          <el-table-column label="序号" type="index" align="center" width="60"/>
          <el-table-column label="推广员编号" prop="dealerCode" align="center"></el-table-column>
          <el-table-column label="推广员名称" prop="memberName" align="center"></el-table-column>
          <el-table-column label="推广员手机号" prop="phone" align="center"></el-table-column>
          <el-table-column label="会员编号" prop="memberCode" align="center"></el-table-column>
          <el-table-column label="状态" prop="enableStatus" align="center">
            <template #default="{row}">
              <el-tag :type="row.enableStatus ? 'success' : 'danger'">{{ row.enableStatus ? '已启用' : '已禁用' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createdTime" align="center">
            <template #default="{row}">
              <span>{{ $date(row.createdTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="240">
            <template #default="{row}">
              <el-button type="primary" icon="Edit" link @click="toUpdate(row)">修改</el-button>
              <el-divider direction="vertical" />
              <el-button 
                :type="row.enableStatus ? 'danger' : 'success'" 
                :icon="row.enableStatus ? 'WarnTriangleFilled' : 'SuccessFilled'" 
                link 
                @click="doUpdateStatus(row)">
                {{row.enableStatus ? '禁用' : '启用'}}
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" icon="Delete" link @click="doDelete(row.dealersId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          class="paging"
          v-show="query.total"
          small
          layout="total, sizes, prev, pager, next, jumper" 
          :current-page="query.current" 
          :page-size="query.size"
          :total="query.total"
          @current-change="load"
          @size-change="sizeChange">
        </el-pagination>
      </el-card>
    </page-mod>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="show" :title="form.dealersId ? '编辑' : '新增'" top="10vh" width="20%" center draggable @close="resetForm">
      <el-form ref="formRef" :model="form" :rules="rules" size="large" label-position="right" label-width="85px">
        <el-form-item v-if="!form.dealersId" label="会员:" prop="memberId" required>
          <el-select
            v-model="form.memberId"
            filterable
            remote
            remote-show-suffix 
            clearable 
            placeholder="请输入会员名称或编号查询"
            :remote-method="loadMember"
            :loading="selectLoading"
            @change="memberChange">
            <el-option v-for="item in members" :key="item.memberId" :label="item.memberName" :value="item.memberId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名:" prop="memberName" required>
          <el-input v-model="form.memberName" placeholder="请输入姓名" clearable/>
        </el-form-item>
        <el-form-item label="手机号码:" prop="phone" required>
          <el-input v-model="form.phone" placeholder="请输入手机号码" clearable/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" size="default" @click="doSubmit">保存</el-button>
        <el-button size="default" @click="show = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="promoter">
  import { getPromoterListPagesApi, cudPromoterApi, updatePromoterStatusApi, getMemberListApi } from '@/api/api'
  import { regexPhone } from '@/utils/utils'
  import { ref, reactive, toRefs, getCurrentInstance, onActivated } from 'vue'

  // 获取注册的全局实列
  const currentThis = getCurrentInstance().appContext.config.globalProperties
  const formRef = ref(null)

  const currentData = reactive({
    loading: false,
    selectLoading: false,
    show: false,
    query: {
      phone: '',
      dealerCode: '',
      enableStatus: '',
      current: 1,
      size: 20,
      total: 0
    },
    form: {
      dealersId: '',
      memberId: '',
      memberName: '',
      phone: ''
    },
    rules: {
      memberId: [{ required: true, message: '请选择会员', trigger: ['blur', 'change'] }],
      memberName: [{ required: true, message: '请输入姓名', trigger: ['blur', 'change'] }],
      phone: [
        { 
          required: true, trigger: ['blur', 'change'], validator: (rule, value, callback) => {
            if(!value) {
              callback(new Error('请输入手机号码'))
            } else {
              if(!regexPhone(value)) {
                callback(new Error('手机号码格式不对，且必须是11位'))
              } else {
                callback()
              }
            }
          } 
        }
      ]
    },
    dataList: [],
    members: []
  })
  let {loading, selectLoading, show, query, form, rules, dataList, members} = toRefs(currentData)

  // 查询
  function load(page) {
    currentData.loading = true
    currentData.query.current = page
    getPromoterListPagesApi(currentData.query).then(res => {
      currentData.loading = false
      if(res.code === '200') {
        currentData.dataList = res.data.pages
        currentData.query.total = res.data.total
      } else {
        currentThis.$message.error(res.message)
      }
    })
  }

  // 新增时候会员下拉选择数据根据输入值查询
  function loadMember(member) {
    if(!member) {
      return
    }
    currentData.selectLoading = true
    getMemberListApi({ member: member }).then(res => {
      currentData.selectLoading = false
      if(res.code === '200') {
        currentData.members = res.data
      }
    })
  }

  // 新增或编辑
  function doSubmit() {
    formRef.value.validate((valid) => {
      if (valid) {
        currentThis.$messageBox.confirm(`确认${currentData.form.dealersId ? '修改' : '新增'}吗？`).then(() => {
          let loading = currentThis.$loading(`正在${currentData.form.dealersId ? '修改' : '新增'}`)
          cudPromoterApi(`${currentData.form.dealersId ? 'update' : 'save'}`, currentData.form).then(res => {
            loading.close()
            if(res.code === '200') {
              currentThis.$message.success(res.message)
              currentData.show = false
              load(currentData.form.dealersId ? currentData.query.current : 1)
            } else {
              currentThis.$message.error(res.message)
            }
          })
        }).catch(() => {})
      } else {
        return false;
      }
    })
  }

  // 修改前弹窗
  function toUpdate(e) {
    currentData.form.dealersId = e.dealersId
    currentData.form.memberName = e.memberName
    currentData.form.phone = e.phone
    currentData.show  = true
  }
  
  // 启用或禁用
  function doUpdateStatus(e) {
    currentThis.$messageBox.confirm(`确认${e.enableStatus ? '禁用' : '启用'}吗？`).then(() => {
      let loading = currentThis.$loading('正在处理，请耐心等待')
      updatePromoterStatusApi(e.dealersId, e.enableStatus ? 0 : 1).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 删除
  function doDelete(dealersId) {
    currentThis.$messageBox.confirm('确认删除吗？').then(() => {
      let loading = currentThis.$loading('正在删除，请耐心等待')
      cudPromoterApi('delete', { 
        id: dealersId 
      }).then(res => {
        loading.close()
        if(res.code === '200') {
          currentThis.$message.success(res.message)
          load(currentData.query.current)
        } else {
          currentThis.$message.error(res.message)
        }
      })
    }).catch(() => {})
  }

  // 新增时候会员下拉选择数据改变时候执行
  function memberChange(memberId) {
    if(memberId) {
      let chooseMember = currentData.members.filter(item => {
        return item.memberId === memberId
      })[0]
      currentData.form.memberName = chooseMember.memberName
      currentData.form.phone = chooseMember.phone
    } else {
      currentData.form.memberName = ''
      currentData.form.phone = ''
    }
  }
  
  // 重置查询
  function resetSearch() {
    currentData.query.phone = ''
    currentData.query.dealerCode = ''
    currentData.query.enableStatus = ''
    load(1)
  }

  // 编辑弹窗关闭重置数据
  function resetForm() {
    currentData.form = {
      dealersId: '',
      memberId: '',
      memberName: '',
      phone: ''
    }
    formRef.value.resetFields()
  }

  // 分页每页显示条数改变执行
  function sizeChange(size) {
    currentData.query.size = size
    load(1)
  }

  onActivated(() => {
    load(currentData.query.current)
  })
</script>

<style lang="less" scoped>
.promoter{
  :deep(.el-dialog){
    .el-input, .el-textarea{
      width: 300px;
    }
    .el-select{
      .el-input{
        width: 250px !important;
      }
    }
  }
}
</style>